'use strict';

angular.module('huaguoApp', [
        'ngCookies',
        'ngResource',
        'ngSanitize',
        'btford.socket-io',
        'ui.router',
        'ui.bootstrap',
        'restangular',
        'ngAnimate',
        'ngStorage',
        'uuid4',
        'ngFileUpload',
        'textAngular'
    ])
    .config(function($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider, RestangularProvider) {
        $urlRouterProvider
            .otherwise('/home');

        //$locationProvider.html5Mode(true);
        $httpProvider.interceptors.push('authInterceptor');
        //RestAngular服务个性化配置
        RestangularProvider.setBaseUrl('/api');
    })
    .factory('authInterceptor', function($rootScope, $q, $cookieStore, $location) {
        return {
            // Add authorization token to headers
            request: function(config) {
                config.headers = config.headers || {};
                if ($cookieStore.get('token')) {
                    config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
                }
                return config;
            },

            // Intercept 401s and redirect you to login
            responseError: function(response) {
                if (response.status === 401) {
                    $location.path('/login');
                    // remove any stale tokens
                    $cookieStore.remove('token');
                    return $q.reject(response);
                } else {
                    return $q.reject(response);
                }
            }
        };
    })

.run(function($rootScope, $location, Auth,$localStorage) {
    // Redirect to login if route requires auth and you're not logged in
    if($localStorage.user){
        $rootScope.plugin=true;
        $rootScope.avator=$localStorage.user.avator;
        $rootScope.username=$localStorage.user.username;
    }else{
        $rootScope.plugin=false;
    }

    $rootScope.$on('$stateChangeStart', function(event, next) {
        Auth.isLoggedInAsync(function(loggedIn) {
            if (next.authenticate && !loggedIn) {
                event.preventDefault();
                $location.path('/login');
            }
        });
    });
});
